package com.example.demo.util;

import com.example.demo.model.User;
import org.springframework.security.crypto.password.StandardPasswordEncoder;

import java.util.Objects;

import static org.apache.shiro.web.filter.mgt.DefaultFilter.user;

public class PasswordUtil {
    public static String encrypt = "sha256";

    public final static String salt = "fhjrgjkffgd";

    /* --------------------- sha256 -------------------------------------------- */
    public static String encryptPassword(String password, String salt) {

        StandardPasswordEncoder encoder = new StandardPasswordEncoder(salt);

        // 加密密码， 多次加密
       return encoder.encode(password);

    }

    public static String encryptPassword(String password) {

        StandardPasswordEncoder encoder = new StandardPasswordEncoder();

        // 加密密码， 多次加密
        return encoder.encode(password);

    }

    public static void encryptPassword(User user, String salt) {
        StandardPasswordEncoder encoder = new StandardPasswordEncoder(salt);
        // 加密密码
        user.setEncryptPassword(encoder.encode(user.getPassword()));
        user.setSalt(salt);
        user.setEncrypt(encrypt);
    }

    public static Boolean matches(CharSequence password, String encodePassword, String encrypt, String salt) {
        if (Objects.equals(PasswordUtil.encrypt, encrypt)) {
            StandardPasswordEncoder encoder = new StandardPasswordEncoder(salt);
            if (encoder.matches(password, encodePassword)) {
                return Boolean.TRUE;
            }
            return false;
        } else {
            return Boolean.FALSE;
        }
    }

    public static Boolean matches(CharSequence password, String encodePassword, CharSequence salt) {
        StandardPasswordEncoder encoder = new StandardPasswordEncoder(salt);
        if (encoder.matches(password, encodePassword)) {
            return Boolean.TRUE;
        }
        return Boolean.FALSE;
    }

    public static Boolean matches(CharSequence password, String encodePassword) {
        StandardPasswordEncoder encoder = new StandardPasswordEncoder();
        if (encoder.matches(password, encodePassword)) {
            return Boolean.TRUE;
        }
        return Boolean.FALSE;
    }
    /* --------------------- sha256 end -------------------------------------- */

    public static void main(String[] args) {
        String pwd  = "1234567890";

        String a1 = PasswordUtil.encryptPassword(pwd, salt);
        String a2 = PasswordUtil.encryptPassword(pwd, salt);
        System.out.println(a1);
        System.out.println(a2);
        System.out.println(PasswordUtil.matches("1234567890", a2, salt));

    }

}
